package com.heatup.apt.management.service.store.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.heatup.apt.common.constants.ServiceConstans;
import com.heatup.apt.common.constants.StoreConstants;
import com.heatup.apt.common.dao.ResourceMapper;
import com.heatup.apt.common.dao.ServicePriceMapper;
import com.heatup.apt.common.dao.TSysCityMapper;
import com.heatup.apt.common.dao.TSysDistriceMapper;
import com.heatup.apt.common.dao.TSysProvinceMapper;
import com.heatup.apt.common.dao.store.StoreInfoMapper;
import com.heatup.apt.management.service.store.StoreService;
import com.heatup.apt.model.Resource;
import com.heatup.apt.model.TSysCity;
import com.heatup.apt.model.TSysDistrice;
import com.heatup.apt.model.TSysProvince;
import com.heatup.apt.model.product.ServicePrice;
import com.heatup.apt.model.store.StoreInfo;
import com.heatup.apt.model.store.StoreInfoRequest;

/**
 * Created by b3st9u on 16/8/22.
 */
@Service
public class StoreServiceImpl implements StoreService {
    @Autowired
    StoreInfoMapper storeInfoMapper;

    @Autowired
    ServicePriceMapper servicePriceMapper;

    @Autowired
    ResourceMapper resourceMapper;

    @Autowired
    TSysProvinceMapper provinceMapper;

    @Autowired
    TSysCityMapper cityMapper;

    @Autowired
    TSysDistriceMapper areaMapper;


    @Override
    public List<StoreInfo> queryAllStore() {
        return storeInfoMapper.selectList(null);
    }

    @Override
    public List<TSysProvince> queryAllProvince() {
        return provinceMapper.queryAllProvince();
    }

    @Override
    public List<TSysCity> queryAllCity() {
        return cityMapper.queryAllCity();
    }

    @Override
    public List<TSysDistrice> queryAllDistrict() {
        return areaMapper.queryAllArea();
    }

    /**
     * 保存门店
     * @param storeInfoRequest
     * @return
     */
    @Override
    public boolean saveStore(StoreInfoRequest storeInfoRequest) {
        int result = 0;
        if (storeInfoRequest == null) {
            return result > 0;
        }

        StoreInfo storeInfo = saveStoreInfo(storeInfoRequest);

        result = saveStorePrice(storeInfoRequest, storeInfo);

        saveStorePic(storeInfoRequest, storeInfo);

        return result > 0;
    }

    /**
     * 保存门店数据
     * @param storeInfoRequest
     * @return
     */
    private StoreInfo saveStoreInfo(StoreInfoRequest storeInfoRequest) {

        StoreInfo storeInfo = new StoreInfo();
        BeanUtils.copyProperties(storeInfoRequest,storeInfo);

        if (storeInfo != null && storeInfo.getIs24Hours() != null && storeInfo.getIs24Hours() == 1) {
            //支持24小时营业则无需开门-结束时间
            storeInfo.setOpenTime(null);
            storeInfo.setCloseTime(null);
        }

        String jwd = storeInfoRequest.getLongitudeAndLatitude();
        if (StringUtils.isNotBlank(jwd)) {
            String[] jwdArr = jwd.split(",");
            storeInfo.setLongitude(new BigDecimal(jwdArr[1]));
            storeInfo.setLatitude(new BigDecimal(jwdArr[0]));
        }
        if(storeInfoRequest.getServices().length() > 0){
        	storeInfo.setServices(storeInfoRequest.getServices().replaceAll(",","#"));
        }
        storeInfo.setCreatedBy(1);
        storeInfo.setVersion(1);
        storeInfo.setCreatedTime(new Date());
        // jxy add 
        if(storeInfoRequest.getManageType() == StoreConstants.StoreManageType.league_manage.getIndex()){
        	if(storeInfoRequest.getUserHasService().length() > 0){
        		storeInfo.setUserHasService(storeInfoRequest.getUserHasService().replaceAll(",","#"));// 用户可使用的服务
        	}
        	if(storeInfoRequest.getUserNotService().length() > 0){
        		storeInfo.setUserNotService(storeInfoRequest.getUserNotService().replaceAll(",","#"));//用户不可使用的服务
        	}
            storeInfo.setNapaStoreTips(storeInfoRequest.getNapaStoreTips());//加盟店温馨提示
        }else{
        	storeInfo.setUserHasService("");// 用户可使用的服务
            storeInfo.setUserNotService("");//用户不可使用的服务
            storeInfo.setNapaStoreTips("");//加盟店温馨提示
            storeInfo.setManageName("");
            storeInfo.setManageContcat("");
        }
        // 防止非空
        if(!StringUtils.isEmpty(storeInfoRequest.getStoreFeatures())){
        	storeInfo.setStoreFeatures(storeInfoRequest.getStoreFeatures().replaceAll(",","#"));// 门店特色
        }
        
        
        if (StringUtils.isNotBlank(storeInfoRequest.getProvince())) {
            storeInfo.setProvinceId(provinceMapper.queryProvinceIdByName(storeInfoRequest.getProvince()));
        }
        if(StringUtils.isNotBlank(storeInfoRequest.getCity()) && storeInfo.getProvinceId()!= null){
            storeInfo.setCityId(cityMapper.queryCityIdByName(storeInfoRequest.getCity(),storeInfo.getProvinceId()));
        }
        if(StringUtils.isNotBlank(storeInfoRequest.getArea()) && storeInfo.getCityId() != null){
            storeInfo.setAreaId(areaMapper.queryAreaIdByName(storeInfoRequest.getArea(),storeInfo.getCityId()));
        }
        return storeInfo;
    }

    /**
     * 保存门店自助健身价格
     * @param storeInfoRequest
     * @param storeInfo
     * @return
     */
    private int saveStorePrice(StoreInfoRequest storeInfoRequest, StoreInfo storeInfo) {
        int result;
        ServicePrice storePrice = null;
        if(storeInfoRequest!=null || storeInfoRequest.getPrimePrice() != null ){
            //支持自助健身
            storePrice = new ServicePrice();
            storePrice.setServiceType(ServiceConstans.ServiceType.selfFitness.getIndex());
            storePrice.setServiceName(ServiceConstans.ServiceType.selfFitness.getTitle());
            storePrice.setPrimePrice(storeInfoRequest.getPrimePrice());//自助健身价格
            if (storeInfoRequest.getPrice() != null) {
                storePrice.setPrice(storeInfoRequest.getPrice());//自助健身会员价格
            }
        }
        if(storeInfoRequest.getId() !=null){

            storeInfo.setId(storeInfoRequest.getId());
            result= storeInfoMapper.updateById(storeInfo);
            if(storePrice!=null){
                storePrice.setId( servicePriceMapper.queryServicePriceIdByStoreId(storeInfo.getId()));
                if(!"0".equals(storeInfo.getIsSelfFitness()) && storePrice.getId() == null 
                		|| !"0".equals(storeInfo.getIsSelfFitness()) && storePrice.getId() == 0){
                	storePrice.setStoreId(storeInfo.getId());
                	servicePriceMapper.insertSelective(storePrice);
                }else{
                	servicePriceMapper.updateByPrimaryKeySelective(storePrice);
                }
                
            }
            //清理关联表数据
            resourceMapper.deleteByStoreId(storeInfo.getId());

        } else{
            storeInfo.setStatus("1");
            //1.  先插入store_info表
            result = storeInfoMapper.insertSelective(storeInfo);
            if(storePrice !=null){
                storePrice.setStoreId(storeInfo.getId());
                servicePriceMapper.insertSelective(storePrice);
            }
        }
        return result;
    }

    /**
     * 保存门店硬照
     * @param storeInfoRequest
     * @param storeInfo
     */
    private void saveStorePic(StoreInfoRequest storeInfoRequest, StoreInfo storeInfo) {
        String catePic = storeInfoRequest.getCategoryPic();
        if (catePic.length() > 0) {
            String[] catePics = catePic.split(",");
            Resource storeResource;
            for (String pic : catePics) {
                storeResource = new Resource();
                storeResource.setParentId(storeInfo.getId());
                storeResource.setParentType("1");
                storeResource.setResType("1");
                storeResource.setResKey("store_category");
                storeResource.setTitle("门店硬照");
                storeResource.setUrl(pic);
                resourceMapper.insertSelective(storeResource);
            }
        }
    }

    /**
     * 分页门店查询
     * @param paramsMap
     * @return
     */
    @Override
    public Map<String, Object> queryStoreList(Map<String, Object> paramsMap) {

        Map<String, Object> resultMap = new HashMap<>();
        paramsMap.put("pageNo", (Integer) paramsMap.get("pageIndex") * (Integer) paramsMap.get("pageSize"));
        paramsMap.put("pageSize", paramsMap.get("pageSize"));
        resultMap.put("storeList", storeInfoMapper.queryStoreList(paramsMap));
        resultMap.put("storeCount", storeInfoMapper.queryStoreCount(paramsMap));

        return resultMap;
    }

    /**
     * 删除门店
     * @param id
     * @return
     */
    @Override
    public boolean delStoreInfoById(Integer id) {
        if (id <= 0)
            throw new RuntimeException("门店ID错误!");
        //清理关联数据

        servicePriceMapper.deleteByStoreId(id);
        resourceMapper.deleteByStoreId(id);
        return storeInfoMapper.deleteById(id) > 0;

    }

    /**
     * 门店开业
     * @param storeInfo
     * @return
     */
    @Override
    public boolean openStoreById(StoreInfo storeInfo) {
        if (storeInfo.getId() <= 0)
            throw new RuntimeException("门店ID错误!");
        storeInfo.setStatus("2");
        return storeInfoMapper.updateSelectiveById(storeInfo) > 0;

    }

    /**
     * 门店即将开业
     *
     * @param storeInfo
     * @return
     */
    @Override
    public boolean readyStoreById(StoreInfo storeInfo) {
        if (storeInfo.getId() <= 0)
            throw new RuntimeException("门店ID错误!");
        storeInfo.setStatus("1");
        return storeInfoMapper.updateSelectiveById(storeInfo) > 0;
    }

    /**
     * 门店停业
     * @param storeInfo
     * @return
     */
    @Override
    public boolean closeStoreById(StoreInfo storeInfo) {
        if (storeInfo.getId() <= 0)
            throw new RuntimeException("门店ID错误!");
        storeInfo.setStatus("4");
        return storeInfoMapper.updateSelectiveById(storeInfo) > 0;

    }

    /**
     * 根据门店ID查询门店
     * @param storeId
     * @return
     */
    @Override
    public StoreInfoRequest queryStoreInfoById(Long storeId) {
        if (storeId <= 0)
            throw new RuntimeException("门店ID错误!");
        StoreInfoRequest storeInfoRequest = storeInfoMapper.queryStoreInfoById(storeId);
        if (storeInfoRequest.getResources() != null && storeInfoRequest.getResources().size() > 0) {
            List<Resource> resources = storeInfoRequest.getResources();
            StringBuilder sCatePic = new StringBuilder();

            for (Resource resource : resources) {
                if (StringUtils.isNotBlank(resource.getResKey()) && resource.getResKey().equalsIgnoreCase("store_category")) {
                    if (sCatePic.length() <= 0) {
                        sCatePic.append(resource.getUrl());
                    } else {
                        sCatePic.append("," + resource.getUrl());
                    }
                }
            }
            storeInfoRequest.setCategoryPic(sCatePic.toString());
        }
        if (StringUtils.isNotBlank(storeInfoRequest.getProvince())) {
            storeInfoRequest.setProvince(provinceMapper.queryProvinceNameById(storeInfoRequest.getProvince()));
        }
        if (StringUtils.isNotBlank(storeInfoRequest.getCity())) {
            storeInfoRequest.setCity(cityMapper.queryCityNameById(storeInfoRequest.getCity()));
        }
        if (StringUtils.isNotBlank(storeInfoRequest.getArea())) {
            storeInfoRequest.setArea(areaMapper.queryAreaNameById(storeInfoRequest.getArea()));
        }

        return storeInfoRequest;
    }

    @Override
    public List<StoreInfo> queryStoreListWithWorkoutRoom() {
        return storeInfoMapper.queryStoreListWithWorkoutRoom();
    }

	@Override
	public List<StoreInfoRequest> queryDataCenterStoreList(String status,String manageType) {
		// TODO Auto-generated method stub
		return storeInfoMapper.queryDataCenterStoreList(status,manageType);
	}

    /**
     * 查询所有在线的门店 只查询营业中的
     *
     * @author blank 2017/9/7 下午3:37
     */
    @Override
    public List<StoreInfo> queryAllOnlineStore() {

        StoreInfo storeInfo = new StoreInfo();
        EntityWrapper<StoreInfo> entityWrapper = new EntityWrapper<>(storeInfo);
        entityWrapper.in("status","2");

        return storeInfoMapper.selectList(entityWrapper);
    }
}
